import React from "react";
import {Switch} from 'antd';
import PropTypes from "prop-types";
import BaseField from "../Base/BaseField";
import BaseFormItem from "../Base/BaseFormItem";
import {isBoolean, isEmpty, omit} from "lodash-es";
import ComboBox from "../ComboBox";

const compData = [
    {code: '0', name: '否'},
    {code: '1', name: '是'}
];

export class SwitchBase extends BaseField {

    static propTypes = {
        ...BaseField.propTypes,

        /**
         * 是否需要在初始组件时，触发 hdlValueChange 事件
         */
        isNotInitChange: PropTypes.bool,
    };

    moreCommonProps() {
        return [...super.moreCommonProps(), 'value', 'defaultValue', 'isNotInitChange'];
    }

    componentDidMount() {
        super.componentDidMount();
        if ('value' in this.props && 'onChange' in this.props
            && !this.props.cell && !isBoolean(this.state.value) && !this.props.isNotInitChange
        ) {
            this.hdlValueChange(false);
        }
    }

    mainRender(context) {
        const style = this.getPropsByName('style') || {};
        const {value} = this.state;
        const {cell} = this.props;

        // cell = true，说明是在可编辑表格里，此时以 ComboBox 替换组件
        if (cell) {

            return (<ComboBox
                {...omit(this.props, this.commonProps)}
                needOptionLocale={true}
                allowClear={true}
                needPH={false}
                compData={compData}
                value={isBoolean(value) ? value ? '1' : '0' : ''}
                onChange={(val) => {
                    this.hdlValueChange('1' === val);
                }}
                ref={(ref) => {
                    this.nodeRef = ref;
                }}
            />)
        }

        return (
            <Switch
                {...omit(this.props, [...this.commonProps, 'defaultOpen'])}
                style={omit(style, ['width', 'height'])}
                checked={value === true}
                onChange={this.hdlValueChange.bind(this)}
                ref={(ref) => {
                    this.nodeRef = ref;
                }}
            />
        )
    }
}

export default class SwitchComp extends BaseFormItem {

    Comp = SwitchBase;
}